<template>
  <div class="addChargingRule-page">
    <breadcrumb />
    <div class="table-container">
      <h3 style="margin-bottom: 20px">{{ pageTitle }}</h3>
      <el-form ref="formRef" :rules="rules" :model="formModel" label-width="160">
        <el-form-item label="策略名称" prop="name">
          <el-input
            v-model="formModel.name"
            style="width: 320px"
            placeholder="请输入策略名称"
          />
        </el-form-item>
        <el-form-item label="计费方式" prop="periodType">
          <el-select
            v-model="formModel.periodType"
            filterable
            style="width: 320px"
            placeholder="请选择计费方式"
            @change="onChangePeriodType"
          >
            <el-option
              v-for="item in periodTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否区分车辆类型" prop="diffVehicleType">
          <el-radio-group
            v-model="formModel.diffVehicleType"
            @change="onchangeDiffVehicle"
          >
            <el-radio
              v-for="item in diffVehicleTypeOptions"
              :key="item.id"
              :value="item.id"
              :label="item.id"
            >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div style="display: flex; align-items: center; margin-bottom: 16px">
        <h3>计费规则明细</h3>
        <el-button type="primary" @click="getAddRules" style="margin-left: 6px"
          >新增</el-button
        >
      </div>
      <RulesTable
        :list="formModel.ruleItemList"
        @delete-data="deleteData"
        @edit-data="editData"
      />
      <RulesItem
        v-if="addRules"
        ref="rulesItemRef"
        :edit-data="ruleItemData"
        :data="formModel"
        @update-rule="updateRule"
        @cancel-rule="cancelRule"
      />
      <ChargingDialog ref="chargingDialogRef" @change-charging="changeCharging" />
      <DiffVehicleTypeDialog
        ref="diffVehicleTypeDialogRef"
        @change-diff-vehicle="changeDiffVehicle"
      />
      <div class="footer">
        <div class="search-btn">
          <el-button class="reset-btn" @click="resetForm">重 置 </el-button>
          <el-button class="confirm-btn" @click="submitForm">确 认 </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import breadcrumb from "@/components/breadcrumb/index.vue";
import { reactive, ref } from "vue";
import { periodTypeOptions, diffVehicleTypeOptions } from "./types";
import RulesTable from "./components/rules-table.vue";
import RulesItem from "./components/rules-item.vue";
import { useRoute, useRouter } from "vue-router";
import ChargingDialog from "./components/charging-dialog.vue";
import DiffVehicleTypeDialog from "./components/diffVehicle-type-dialog.vue";
import { ElMessage } from "element-plus";
import { getAddCpark, getEditCpark, getCparkChargeRuleForm } from "./request";
import { generateUUID } from "../../../../utils/common";

const router = useRouter();
const route = useRoute();
const pageTitle = ref("新增计费策略");
const formModel = ref({
  periodType: 1,
  diffVehicleType: 1,
  ruleItemList: [],
});
const id = ref("");
const formRef = ref("");
const rulesItemRef = ref("");
const chargingDialogRef = ref("");
const chargingDialogValue = ref();
const diffVehicleTypeDialogRef = ref("");
const diffVehicleTypeDialogValue = ref();
const rulesNmae = ref("");
const ruleItemData = ref({});
const addRules = ref(true);
const rules = reactive({
  name: [{ required: true, message: "请输入策略名称", trigger: "blur" }],
  periodType: [{ required: true, message: "请选择计费方式" }],
  diffVehicleType: [
    { required: true, message: "请选择是否区分车辆类型", trigger: "change" },
  ],
});

const onChangePeriodType = (val) => {
  chargingDialogRef.value?.init();
  chargingDialogValue.value = val;
  rulesNmae.value = formModel.value.name;
};
const onchangeDiffVehicle = (val) => {
  diffVehicleTypeDialogRef.value?.init();
  diffVehicleTypeDialogValue.value = val;
  rulesNmae.value = formModel.value.name;
};
const getAddRules = () => {
  addRules.value = true;
};
const changeCharging = () => {
  // if (rulesItemRef.value) {
  //   rulesItemRef.value.resetRulesItem(true);
  // }
  formModel.value = {
    diffVehicleType: formModel.value.diffVehicleType,
    ruleItemList: [],
  };
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
  formModel.value.periodType = chargingDialogValue.value;
  formModel.value.name = rulesNmae.value;
};
const changeDiffVehicle = () => {
  // if (rulesItemRef.value) {
  //   rulesItemRef.value.resetRulesItem(true);
  // }
  formModel.value = {
    periodType: formModel.value.periodType,
    ruleItemList: [],
  };
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
  formModel.value.diffVehicleType = diffVehicleTypeDialogValue.value;
  formModel.value.name = rulesNmae.value;
};
const resetForm = () => {
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
  formModel.value = {
    periodType: 1,
    diffVehicleType: 1,
    ruleItemList: [],
  };
  addRules.value = true;
};
const updateRule = (data) => {
  data.forEach((item) => {
    const result = formModel.value.ruleItemList.find((el) => el.uuid === item.uuid);
    if (result) {
      for (let i = 0; i < formModel.value.ruleItemList.length; i++) {
        if (formModel.value.ruleItemList[i].uuid === item.uuid) {
          formModel.value.ruleItemList[i] = item;
        }
      }
    } else {
      formModel.value.ruleItemList.push(item);
    }
  });
  addRules.value = false;
  ruleItemData.value = {};
};
const cancelRule = () => {
  addRules.value = false;
  ruleItemData.value = {};
};
const deleteData = (index) => {
  formModel.value.ruleItemList.splice(index, 1);
};
const editData = (data) => {
  ruleItemData.value = data;
  addRules.value = true;
};
const submitForm = async () => {
  await formRef.value.validate();
  if (formModel.value.ruleItemList.length < 1) {
    ElMessage.error("计费规则明细配置不完整");
    return;
  }
  try {
    const fn = id.value ? getEditCpark : getAddCpark;
    const params = id.value ? { id: id.value, data: formModel.value } : formModel.value;
    console.log("fn", id.value);
    const { data } = await fn(params);
    ElMessage({
      type: "success",
      message: data.result,
    });
    if (data.code === 0) {
      router.go(-1);
    }
  } catch (error) {
    console.log("新增规则报错", error);
  }
};
const getFormData = async (id) => {
  try {
    const { data } = await getCparkChargeRuleForm(id);
    formModel.value.diffVehicleType = data.result.diffVehicleType ? 1 : 0;
    formModel.value.id = data.result.id;
    formModel.value.name = data.result.name;
    formModel.value.periodType = data.result.periodType;
    formModel.value.ruleItemList = data.result.ruleItemList.map((el) => {
      el.uuid = generateUUID();
      return el;
    });
  } catch (error) {
    console.log("获取数据出错", error);
  }
};
router.isReady().then(() => {
  if (route.query?.data) {
    const formId = JSON.parse(decodeURIComponent(route.query.data));
    id.value = formId;
    pageTitle.value = "编辑计费策略";
    getFormData(formId);
    addRules.value = false;
  }
});
</script>
<style lang="less" scoped>
.table-container {
  margin-top: 16px;
  min-height: 100%;
  padding: 24px;
  background: #fff;
  border-radius: 6px;
}
.billing-detail {
  background: #f2f7fc;
  padding: 20px;
  margin-top: 24px;
}
.footer {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
  margin-top: 24px;
  .search-btn {
    display: flex;
    .reset-btn {
      width: 65px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #d9d9d9;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
    }

    .confirm-btn {
      width: 65px;
      height: 32px;
      background: #007aff;
      border-radius: 2px;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
    }
  }
}
</style>
